<?php
namespace app\backstage\controller;
use think\Controller;
use think\Db;
use think\facade\Request;

class Cost extends Controller
{
    protected $middleware = [
        'VerifyJwt' => ['except' => []],
        'VerifyPower' => ['except' => []],
    ];

    public function index()
    {
        $Account = \think\facade\App::model('Account', 'logic');
        $agentId = request()->_role->alias == 'agent' ? request()->_user->id : 0;

        $channels = $Account->getChannels($agentId);

        $this->assign('channels',$channels);
        $this->assign('role_name',request()->_role->alias);
        return $this->fetch();
    }

    public function list_data()
    {
        $params = Request::param('', '', 'strip_tags');
        $CostManual = \think\facade\App::model('CostManual', 'logic');
        $result = $CostManual->getList($params);

        return sucJson($result['list'], $result['count']);
    }

    public function add()
    {
        if( Request::isGet() ){

            $agentId = request()->_role->alias == 'agent' ? request()->_user->id : 0;
            $Account = \think\facade\App::model('Account', 'logic');
            $channels = $Account->getChannels($agentId);

            $where = [];
            if(request()->_role->alias == 'agent')
            {
                $where[] = ['channel_id','in',array_column($channels,'id')];
            }
            if(request()->_role->alias == 'channel')
            {
                $where[] = ['channel_id','=',request()->_user->id];
            }

            $Link = \think\facade\App::model('Link', 'logic');
            $links = $Link->getAllList($where);

            $this->assign('links', $links);
            $this->assign('advert_medias',advertMediaList());
            $this->assign('channels',$channels);
            $this->assign('role_name',request()->_role->alias);
            return $this->fetch();
        }

        $params = Request::post('','','strip_tags,trim');

        if(request()->_role->alias == 'agent')
        {
            $verify_result = $this->validate($params, 'CostManual.add_agent'.$params['type']);
        }else{
            $verify_result = $this->validate($params, 'CostManual.add'.$params['type']);
        }

        if(true !== $verify_result){
            return json(['code'=>101,'msg'=>$verify_result]);
        }

        if (request()->_role->alias == 'agent') {

            $channel_ids = Db::table('cms_manager_user')->where('parent_id','=',request()->_user->id)
                ->column('id');

            if(!$channel_ids){
                return json(['code'=>101,'msg'=>'该记录未归属给该代理，请核实后操作']);
            }

            if(!in_array($params['channel_id'],$channel_ids))
            {
                return json(['code'=>101,'msg'=>'该记录未归属给该代理，请核实后操作']);
            }

        }else{
            $params['channel_id'] = request()->_user->id;
        }

        $CostManual = \think\facade\App::model('CostManual','logic');

        $where[] = ['channel_id','=',$params['channel_id']];
        $where[] = ['cost_date','=',$params['cost_date']];

        if($params['type'] == 2)
        {
            $where[] = ['advert_media_id','=',$params['advert_media_id']];
        }
        if($params['type'] == 3)
        {
            $where[] = ['link_id','=',$params['link_id']];
        }

        $record = Db::table('rp_cost_manual')->where($where)->field('id')->findOrEmpty();

        if($record){

            if($params['type'] == 1)
            {
                return json(['code'=>101,'msg'=>'该投放号在当日已存在消耗金额，请勿重复添加']);
            }
            if($params['type'] == 2)
            {
                return json(['code'=>101,'msg'=>'该投放号在当日该投放媒体已存在消耗金额，请勿重复添加']);
            }
            if($params['type'] == 3)
            {
                return json(['code'=>101,'msg'=>'该投放号在当日该推广链接已存在消耗金额，请勿重复添加']);
            }

        }

        $data   = $CostManual->dataProcessing($params);
        $result = $CostManual->addInfo($data['data']);

        if($result['code'] == 100)
        {
            $this->updateReport($data['data']);
        }

        return json($result);
    }

    public function preview()
    {
        $params = Request::param('', '', 'strip_tags');

        $where[] = ['id','=',$params['id']];

        if (request()->_role->alias == 'channel') {
            $where[] = ['channel_id','=',request()->_user->id];
        }

        $CostManual = \think\facade\App::model('CostManual','logic');
        $info = $CostManual->getInfo($where);

        if(!$info){
            $this->error('该信息记录不存在');
        }
        
        $info['money'] = getQuotient($info['money'],100);

        $agentId = request()->_role->alias == 'agent' ? request()->_user->id : 0;
        $Account = \think\facade\App::model('Account', 'logic');
        $channels = $Account->getChannels($agentId);

        $where = [];
        if(request()->_role->alias == 'agent')
        {
            $where[] = ['channel_id','in',array_column($channels,'id')];
        }
        if(request()->_role->alias == 'channel')
        {
            $where[] = ['channel_id','=',request()->_user->id];
        }

        $Link = \think\facade\App::model('Link', 'logic');
        $links = $Link->getAllList($where);

        $this->assign('links', $links);
        $this->assign('advert_medias',advertMediaList());
        $this->assign('channels',$channels);
        $this->assign('role_name',request()->_role->alias);
        $this->assign('info',$info);
        return $this->fetch();
    }

    public function edit()
    {
        $params = Request::post('','','strip_tags,trim');

        if(request()->_role->alias == 'agent')
        {
            $verify_result = $this->validate($params, 'CostManual.edit_agent'.$params['type']);
        }else{
            $verify_result = $this->validate($params, 'CostManual.edit'.$params['type']);
        }

        if(true !== $verify_result){
            return json(['code'=>101,'msg'=>$verify_result]);
        }

        if (request()->_role->alias == 'agent') {

            $channel_ids = Db::table('cms_manager_user')->where('parent_id','=',request()->_user->id)
                ->column('id');

            if(!$channel_ids){
                return json(['code'=>101,'msg'=>'该记录未归属给该代理，请核实后操作']);
            }

            if(!in_array($params['channel_id'],$channel_ids))
            {
                return json(['code'=>101,'msg'=>'该记录未归属给该代理，请核实后操作']);
            }

        }else{
            $params['channel_id'] = request()->_user->id;
        }

        $CostManual = \think\facade\App::model('CostManual','logic');

        $where[] = ['channel_id','=',$params['channel_id']];
        $where[] = ['cost_date','=',$params['cost_date']];

        $record_has = Db::table('rp_cost_manual')->where($where)->field('id')->findOrEmpty();
        if(empty($record_has))
        {
            return json(['code'=>101,'msg'=>'该记录未归属于该投放号，请勿操作']);
        }


        if($params['type'] == 2)
        {
            $where[] = ['advert_media_id','=',$params['advert_media_id']];
        }
        if($params['type'] == 3)
        {
            $where[] = ['link_id','=',$params['link_id']];
        }

        $record = Db::table('rp_cost_manual')->where($where)->field('id')->findOrEmpty();

        if($record && $record['id'] != $params['id']){
            if($params['type'] == 1)
            {
                return json(['code'=>101,'msg'=>'该投放号在当日已存在消耗金额，请勿重复添加']);
            }
            if($params['type'] == 2)
            {
                return json(['code'=>101,'msg'=>'该投放号在当日该投放媒体已存在消耗金额，请勿重复添加']);
            }
            if($params['type'] == 3)
            {
                return json(['code'=>101,'msg'=>'该投放号在当日该推广链接已存在消耗金额，请勿重复添加']);
            }
        }

        $where_up[] = ['id','=',$params['id']];

        $data   = $CostManual->dataProcessing($params);
        $result = $CostManual->editInfo($where_up,$data['data']);

        if($result['code'] == 100)
        {
            $this->updateReport($data['data']);
        }

        return json($result);
    }

    /*数据删除*/
    public function delete()
    {
        $params = Request::param();
        $verify_result = $this->validate($params, 'AdvertUser.info');

        if(true !== $verify_result){
            $this->error($verify_result);
        }

        $CostManual = \think\facade\App::model('CostManual','logic');

        $where[] = ['id','in',$params['id']];

        $info = $CostManual->getInfo($where);

        if (request()->_role->alias == 'agent') {

            $channel_ids = Db::table('cms_manager_user')->where('parent_id','=',request()->_user->id)
                ->column('id');

            if(!$channel_ids){
                return json(['code'=>101,'msg'=>'该记录未归属给该代理，请核实后操作']);
            }

            if(!in_array($info['channel_id'],$channel_ids))
            {
                return json(['code'=>101,'msg'=>'该记录未归属给该代理，请核实后操作']);
            }

        }else{
            $where[] = ['channel_id', '=', request()->_user->id];
        }

        $result  = $CostManual->delInfo($where);

        return json($result);
    }

    /*更新回收报表和复充报表成本数据*/
    private function updateReport($params)
    {
        $start_date = date('Y-m-d', strtotime('-29 day', strtotime($params['cost_date'])));
        $end_date = $params['cost_date'];

        $date_rang = getDateByRange($start_date, $end_date);

        foreach ($date_rang as $date)
        {
            $data = $this->updateTotalCost($date,'agent_id',$params['agent_id'],1,'','');

            Db::table('rp_recycling_report_daily_agent')
                ->where('agent_id',$params['agent_id'])->where('report_date',$date)->update($data);

            $list2 = Db::table('rp_recycling_report_daily_agent_book')->where('agent_id',$params['agent_id'])
                ->where('report_date',$date)->field('id,nid')->select();

            foreach ($list2 as $v)
            {
                $data2 = $this->updateTotalCost($date,'agent_id',$params['agent_id'],3,'nid',$v['nid']);
                Db::table('rp_recycling_report_daily_agent_book')->where('id',$v['id'])->update($data2);
            }

            $list3 = Db::table('rp_recycling_report_daily_agent_link')->where('agent_id',$params['agent_id'])
                ->where('report_date',$date)->field('id,link_id')->select();

            foreach ($list3 as $v)
            {
                $data3 = $this->updateTotalCost($date,'agent_id',$params['agent_id'],3,'link_id',$v['link_id']);
                Db::table('rp_recycling_report_daily_agent_link')->where('id',$v['id'])->update($data3);
            }

            $list4 = Db::table('rp_recycling_report_daily_agent_media')->where('agent_id',$params['agent_id'])
                ->where('report_date',$date)->field('id,advert_media_id')->select();

            foreach ($list4 as $v)
            {
                $data4 = $this->updateTotalCost($date,'agent_id',$params['agent_id'],2,'advert_media_id',$v['advert_media_id']);
                Db::table('rp_recycling_report_daily_agent_media')->where('id',$v['id'])->update($data4);
            }

            $list5 = Db::table('rp_recycling_report_daily_agent_quick')->where('agent_id',$params['agent_id'])
                ->where('report_date',$date)->field('id,quick_id')->select();

            foreach ($list5 as $v)
            {
                $data5 = $this->updateTotalCost($date,'agent_id',$params['agent_id'],1,'quick_id',$v['quick_id']);
                Db::table('rp_recycling_report_daily_agent_quick')->where('id',$v['id'])->update($data5);
            }

            $data6 = $this->updateTotalCost($date,'channel_id',$params['channel_id'],1,'','');

            Db::table('rp_recycling_report_daily_channel')
                ->where('channel_id',$params['channel_id'])->where('report_date',$date)->update($data6);

            $list7 = Db::table('rp_recycling_report_daily_channel_book')->where('channel_id',$params['channel_id'])
                ->where('report_date',$date)->field('id,nid')->select();

            foreach ($list7 as $v)
            {
                $data7 = $this->updateTotalCost($date,'channel_id',$params['channel_id'],3,'nid',$v['nid']);
                Db::table('rp_recycling_report_daily_channel_book')->where('id',$v['id'])->update($data7);
            }

            $list8 = Db::table('rp_recycling_report_daily_channel_link')->where('channel_id',$params['channel_id'])
                ->where('report_date',$date)->field('id,link_id')->select();

            foreach ($list8 as $v)
            {
                $data8 = $this->updateTotalCost($date,'channel_id',$params['channel_id'],3,'link_id',$v['link_id']);
                Db::table('rp_recycling_report_daily_channel_link')->where('id',$v['id'])->update($data8);
            }

            $list9 = Db::table('rp_recycling_report_daily_channel_media')->where('channel_id',$params['channel_id'])
                ->where('report_date',$date)->field('id,advert_media_id')->select();

            foreach ($list9 as $v)
            {
                $data9 = $this->updateTotalCost($date,'channel_id',$params['channel_id'],2,'advert_media_id',$v['advert_media_id']);
                Db::table('rp_recycling_report_daily_channel_media')->where('id',$v['id'])->update($data9);
            }

            $list10 = Db::table('rp_recycling_report_daily_channel_quick')->where('channel_id',$params['channel_id'])
                ->where('report_date',$date)->field('id,quick_id')->select();

            foreach ($list10 as $v)
            {
                $data10 = $this->updateTotalCost($date,'channel_id',$params['channel_id'],1,'quick_id',$v['quick_id']);
                Db::table('rp_recycling_report_daily_channel_quick')->where('id',$v['id'])->update($data10);
            }

            $record = Db::table('rp_recharge_repeated_daily_channel')
                ->where('channel_id',$params['channel_id'])->where('report_date',$date)
                ->field('accumulated_recharge_money,new_jiazhuo_num,accumulated_recharge_num')->findOrEmpty();
            $data11 = $this->updateTotalCost($date,'channel_id',$params['channel_id'],1,'','');

            $data11['profit'] =  $record && $record['accumulated_recharge_money'] > 0 ? $record['accumulated_recharge_money']-$data11['total_cost'] : 0;
            $data11['order_cost'] = $record ? getQuotient($data11['total_cost'],$record['accumulated_recharge_num']) : 0;
            $data11['jiazhuo_cost'] = $record ? getQuotient($data11['total_cost'],$record['new_jiazhuo_num']) : 0;

            Db::table('rp_recharge_repeated_daily_channel')
                ->where('channel_id',$params['channel_id'])->where('report_date',$date)
                ->update(['cost'=>$data11['total_cost'],'profit'=>$data11['profit'],'order_cost'=>$data11['order_cost'],'jiazhuo_cost'=>$data11['jiazhuo_cost']]);

            $record2 = Db::table('rp_recharge_repeated_daily_agent')
                ->where('agent_id',$params['agent_id'])->where('report_date',$date)
                ->field('accumulated_recharge_money,new_jiazhuo_num,accumulated_recharge_num')->findOrEmpty();
            $data12 = $this->updateTotalCost($date,'agent_id',$params['agent_id'],1,'','');

            $data12['profit'] =  $record2 && $record2['accumulated_recharge_money'] > 0 ? $record2['accumulated_recharge_money']-$data12['total_cost'] : 0;
            $data12['order_cost'] = $record2 ? getQuotient($data12['total_cost'],$record2['accumulated_recharge_num']) : 0;
            $data12['jiazhuo_cost'] = $record2 ? getQuotient($data12['total_cost'],$record2['new_jiazhuo_num']) : 0;

            Db::table('rp_recharge_repeated_daily_agent')
                ->where('agent_id',$params['agent_id'])->where('report_date',$date)
                ->update(['cost'=>$data12['total_cost'],'profit'=>$data12['profit'],'order_cost'=>$data12['order_cost'],'jiazhuo_cost'=>$data12['jiazhuo_cost']]);

            $record3 = Db::table('rp_recharge_repeated_daily')
                ->where('report_date',$date)
                ->field('accumulated_recharge_money,new_jiazhuo_num,accumulated_recharge_num')->findOrEmpty();
            $data13 = $this->updateTotalCost($date,'cost_date','',1,'','');

            $data13['profit'] =  $record3 && $record3['accumulated_recharge_money'] > 0 ? $record3['accumulated_recharge_money']-$data13['total_cost'] : 0;
            $data13['order_cost'] = $record3 ? getQuotient($data13['total_cost'],$record3['accumulated_recharge_num']) : 0;
            $data13['jiazhuo_cost'] = $record3 ? getQuotient($data13['total_cost'],$record3['new_jiazhuo_num']) : 0;

            Db::table('rp_recharge_repeated_daily')
                ->where('report_date',$date)
                ->update(['cost'=>$data13['total_cost'],'profit'=>$data13['profit'],'order_cost'=>$data13['order_cost'],'jiazhuo_cost'=>$data13['jiazhuo_cost']]);
        }

    }

    /*获取成本数据*/
    private function updateTotalCost($cost_date,$afield,$afieldVal,$type,$cfield,$cval)
    {
        $end_date = date('Y-m-d', strtotime('+29 day', strtotime($cost_date)));

        if(strlen($cfield) > 1)
        {
            $total_cost_ag = Db::table('rp_cost_manual')
                ->where('cost_date',$cost_date)
                ->where($afield,$afieldVal)
                ->where('type',$type)
                ->where($cfield,$cval)
                ->sum('money');
            $data['total_cost'] = $total_cost_ag;

            $accumulated_total_cost_ag = Db::table('rp_cost_manual')
                ->where($afield,$afieldVal)
                ->where('type',$type)
                ->where($cfield,$cval)
                ->where('cost_date','>=',$cost_date)
                ->where('cost_date','<=',$end_date)
                ->sum('money');
            $data['accumulated_total_cost'] = $accumulated_total_cost_ag;
        }else{

            if($afield == 'cost_date')
            {
                $total_cost_ag = Db::table('rp_cost_manual')
                    ->where('cost_date',$cost_date)
                    ->where('type',$type)
                    ->sum('money');
                $data['total_cost'] = $total_cost_ag;

                $accumulated_total_cost_ag = Db::table('rp_cost_manual')
                    ->where('type',$type)
                    ->where('cost_date','>=',$cost_date)
                    ->where('cost_date','<=',$end_date)
                    ->sum('money');
                $data['accumulated_total_cost'] = $accumulated_total_cost_ag;
            }else{
                $total_cost_ag = Db::table('rp_cost_manual')
                    ->where('cost_date',$cost_date)
                    ->where($afield,$afieldVal)
                    ->where('type',$type)
                    ->sum('money');
                $data['total_cost'] = $total_cost_ag;

                $accumulated_total_cost_ag = Db::table('rp_cost_manual')
                    ->where($afield,$afieldVal)
                    ->where('type',$type)
                    ->where('cost_date','>=',$cost_date)
                    ->where('cost_date','<=',$end_date)
                    ->sum('money');
                $data['accumulated_total_cost'] = $accumulated_total_cost_ag;
            }

        }

        return $data;
    }

}